<template>
  <div>
    <BasicTable
      @register="registerTable"
      :dataSource="tableData"
      rowKey="Id"
      title="偏差"
      :columns="columns"
      :maxHeight="200"
      :showIndexColumn="false"
      :clickToRowSelect="false"
      :bordered="true"
      :pagination="false"
      :canResize="false"
      :rowSelection="{
        type: 'checkbox',
        checkStrictly: true,
        onChange(selectedRowKeys) {
          onChangeByTable(selectedRowKeys);
        },
      }"
    >
      <template #headerCell="{ column }">
        <template v-if="column.key === 'Description'">
          <span>
            {{ column.customTitle }}
          </span>
        </template>
        <template v-else>
          <span> {{ column.customTitle }}<span style="color: #ff4d4f">*</span> </span>
        </template>
      </template>
      <template #toolbar>
        <a-input-number v-model:value="deadZone" style="width: 30% !important">
          <template #addonBefore>
            <span>死区</span>
          </template>
        </a-input-number>
        <a-button type="primary" @click="handleAdd"> 新增 </a-button>
        <a-button v-if="isShowBatchDel" type="primary" @click="handleBatchDel"> 删除 </a-button>
      </template>
    </BasicTable>
  </div>
</template>

<script setup lang="ts">
  import { ref, h } from 'vue';
  import { BasicTable, useTable, BasicColumn } from '/@/components/Table';
  // import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { InputNumber } from 'ant-design-vue';
  import { checkNameByTable } from '/@/utils/index';

  const AInputNumber = InputNumber;
  const props = defineProps({
    list: {
      type: Object,
      default: () => {},
    },
  });
  console.log(`output->props`, props);
  const { createConfirm, createMessage } = useMessage();
  // const { t } = useI18n();
  let deadZone = ref(0);
  let isShowBatchDel = ref(false);
  const columns: BasicColumn[] = [
    {
      title: 'key',
      dataIndex: 'Id',
      width: 0,
    },
    {
      title: '是否启用',
      dataIndex: 'IsEnable',
      edit: true,
      editable: true,
      isShowEditBtn: false,
      editComponent: 'Switch',
      width: 80,
    },
    {
      title: '类型',
      dataIndex: 'AlarmStringType',
      edit: true,
      editable: true,
      isShowEditBtn: false,
      editRule: async (text) => checkNameByTable(text, '类型', tableData.value),
      width: 200,
    },
    {
      title: '目标值',
      dataIndex: 'Value',
      edit: true,
      editable: true,
      isShowEditBtn: false,
      editRule: true,
      editComponent: 'InputNumber',
      width: 200,
    },
    {
      title: '偏差',
      dataIndex: 'DeviationValue',
      edit: true,
      editable: true,
      isShowEditBtn: false,
      editRule: true,
      editComponent: 'InputNumber',
      width: 200,
    },
    {
      title: '级别',
      dataIndex: 'AlarmLevel',
      edit: true,
      editable: true,
      isShowEditBtn: false,
      editRule: true,
      editComponent: 'Select',
      editComponentProps: {
        options: [
          {
            label: '信息',
            value: 0,
          },
          {
            label: '次要',
            value: 1,
          },
          {
            label: '一般',
            value: 2,
          },
          {
            label: '主要',
            value: 3,
          },
          {
            label: '严重',
            value: 4,
          },
        ],
      },
      width: 200,
    },
    {
      title: '描述',
      dataIndex: 'Description',
      edit: true,
      editable: true,
      editRule: true,
      isShowEditBtn: false,
      width: 200,
    },
  ];
  let tableData: any = ref([]);
  let delData = [];

  const [registerTable, { getSelectRowKeys, clearSelectedRowKeys }] = useTable();
  // 表格选中事件
  function onChangeByTable(selectedRowKeys) {
    isShowBatchDel.value = selectedRowKeys.length > 0;
  }
  // 新增一条
  function handleAdd() {
    let Id = tableData.value.length + 1;
    tableData.value.push({
      IsEnable: true,
      AlarmStringType: '',
      Value: '',
      AlarmLevel: 0,
      DeviationValue: '',
      Description: '',
      Id,
    });
  }
  // 批量删除
  function handleBatchDel() {
    let keys = getSelectRowKeys();
    let targetNames = tableData.value
      .filter((item) => keys.indexOf(item.Id) >= 0)
      .map((item) => item.AlarmStringType)
      .join('、');
    createConfirm({
      iconType: 'warning',
      title: () => h('span', '温馨提示'),
      okText: '确认',
      content: () => h('span', `是否确认删除选中的定值(${targetNames})`),
      onOk: async () => {
        clearSelectedRowKeys();
        delData = tableData.value
          .filter((item) => keys.indexOf(item.Id) >= 0 && item.Uuid)
          .map((item) => item.Uuid);
        tableData.value = tableData.value.filter((item) => keys.indexOf(item.Id) === -1);
        // createMessage.success(t('layout.setting.operatingTitle'));
      },
    });
  }
  // 设置值方法
  function setValue(val) {
    delData = [];
    tableData.value = val.map((item, i) => {
      item.Id = i;
      return item;
    });
    deadZone.value = val[0] ? val[0].Deadband : 0;
  }
  // 获取值方法
  function getValue() {
    return new Promise<void>((resolve, reject) => {
      let errList: any = [];
      tableData.value.forEach((v) => {
        [null, undefined, ''].indexOf(v.AlarmStringType) >= 0 && errList.push('偏差-类型不能为空');
        tableData.value.filter((item) => item.AlarmStringType === v.AlarmStringType).length >= 2 &&
          errList.push('偏差-类型名不能重复');
        [null, undefined, ''].indexOf(v.Value) >= 0 && errList.push('偏差-目标值不能为空');
        [null, undefined, ''].indexOf(v.DeviationValue) >= 0 && errList.push('偏差-偏差不能为空');
        [null, undefined, ''].indexOf(v.AlarmLevel) >= 0 && errList.push('偏差-级别不能为空');
      });
      if (errList.length > 0) {
        createMessage.error(errList[0]);
        reject(false);
      } else {
        let arr = tableData.value.map((item) => {
          return {
            IsEnable: item.IsEnable,
            AlarmStringType: item.AlarmStringType,
            Value: item.Value,
            AlarmLevel: item.AlarmLevel,
            DeviationValue: item.DeviationValue,
            Description: item.Description,
            Uuid: item.Uuid || '',
            Deadband: deadZone.value || 0,
          };
        });
        resolve({ tableData: arr, delData });
      }
    });
  }
  defineExpose({ getValue, setValue });
</script>

<style scoped></style>
